/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.skatiger.jrove.compiler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.el.ELException;

import org.skatiger.jrove.JroveContext;
import org.skatiger.jrove.JroveException;
import org.skatiger.jrove.JroveHandler;
import org.skatiger.jrove.component.UIComponent;
import org.skatiger.jrove.tag.CompositeHandler;

class CompilationUnit {

    protected final static JroveHandler LEAF = new JroveHandler() {
        public void apply(JroveContext ctx, UIComponent parent) throws IOException, JroveException, ELException {
        }

        @Override
        public String toString() {
            return "JroveHandler Tail";
        }
    };

    private List<CompilationUnit> children;

    public CompilationUnit() {
    }

    public void addChild(CompilationUnit unit) {
        if (this.children == null) {
            this.children = new ArrayList<CompilationUnit>();
        }
        this.children.add(unit);
    }

    public JroveHandler createJroveHandler() {
        return this.getNextJroveHandler();
    }

    protected final JroveHandler getNextJroveHandler() {
        //
        if (this.children == null || this.children.size() == 0) {
            return LEAF;
        }
        if (this.children.size() == 1) {
            CompilationUnit u = (CompilationUnit) this.children.get(0);
            return u.createJroveHandler();
        }
        JroveHandler[] fh = new JroveHandler[this.children.size()];
        for (int i = 0; i < fh.length; i++) {
            fh[i] = ((CompilationUnit) this.children.get(i)).createJroveHandler();
        }
        return new CompositeHandler(fh);
    }

}
